// 动态加载 iconfont.cn 生成的 symbol 脚本（一个或多个）
// 使用：loadIconfont(["//at.alicdn.com/t/c/font_xxx.js"]) 在 main.js 中调用

export function loadIconfont(urls) {
  try {
    const list = normalizeToArray(urls)
    if (list.length === 0) return
    let loadedCount = 0

    list.forEach((url) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onload = () => {
        loadedCount += 1
        cacheSymbolIds()
        if (loadedCount === list.length) {
          window.__ICONFONT_READY__ = true
          window.dispatchEvent(new CustomEvent('iconfont:ready'))
        }
      }
      script.onerror = () => {
        // 单个失败也不阻塞，保持回退到内置图标
      }
      document.body.appendChild(script)
    })
  } catch (e) {
    // 忽略，使用内置图标
  }
}

function normalizeToArray(value) {
  if (!value) return []
  if (Array.isArray(value)) return value.filter(Boolean)
  if (typeof value === 'string') {
    return value
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean)
  }
  return []
}

function cacheSymbolIds() {
  try {
    const symbols = document.querySelectorAll('svg symbol[id]')
    const set = new Set()
    symbols.forEach(s => set.add(s.id))
    window.__ICONFONT_SYMBOL_SET__ = set
  } catch (e) {
    // 忽略
  }
}


